<template>
  <div class="farmer-product-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <div class="page-title">
        <i class="el-icon-goods title-icon"></i>
        <h2>果农商品管理</h2>
      </div>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-s-home" @click="goToHome">返回主页</el-button>
        <el-button type="success" @click="handleAdd" class="el-icon-plus">添加商品</el-button>
      </div>
    </div>

    <!-- 商品表格 -->
    <div class="table-section animate__animated animate__fadeInUp">
      <el-table 
        :data="tableData" 
        border 
        stripe 
        :header-cell-style="getRowClass"
        style="width: 100%">
        <el-table-column prop="productId" label="商品ID" width="80"></el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="origin" label="产地"></el-table-column>
        <el-table-column prop="traceCode" label="溯源码"></el-table-column>
        <el-table-column prop="auditStatusText" label="审核状态">
          <template slot-scope="scope">
            <el-tag :type="getAuditStatusType(scope.row.auditStatus)">{{ scope.row.auditStatusText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditComment" label="审核意见"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="primary" @click="handleView(scope.row)" class="el-icon-view">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加/查看商品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="100px" :rules="rules" ref="productForm">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" :disabled="viewMode"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :min="0" :disabled="viewMode"></el-input-number>
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="form.origin" :disabled="viewMode"></el-input>
        </el-form-item>
        <!-- 隐藏溯源码输入框，仅在查看模式下显示 -->
        <el-form-item label="溯源码" prop="traceCode" v-if="viewMode">
          <el-input v-model="form.traceCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="最低温度" prop="minTemp">
          <el-input-number v-model="form.minTemp" :disabled="viewMode" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="最高温度" prop="maxTemp">
          <el-input-number v-model="form.maxTemp" :disabled="viewMode" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="采摘时间" prop="harvestTime">
          <el-date-picker 
            v-model="form.harvestTime" 
            type="datetime" 
            :disabled="viewMode"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="3" :disabled="viewMode"></el-input>
        </el-form-item>
        
        <!-- 审核信息，仅查看模式显示 -->
        <div v-if="viewMode && form.auditStatus !== null">
          <el-divider>审核信息</el-divider>
          <el-form-item label="审核状态">
            <el-tag :type="getAuditStatusType(form.auditStatus)">{{ getAuditStatusText(form.auditStatus) }}</el-tag>
          </el-form-item>
          <el-form-item label="审核时间" v-if="form.auditTime">
            <span>{{ form.auditTime }}</span>
          </el-form-item>
          <el-form-item label="审核意见" v-if="form.auditComment">
            <span>{{ form.auditComment }}</span>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" v-if="!viewMode">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: 'FarmerProduct',
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加商品',
      viewMode: false,
      form: {
        name: '',
        price: 0,
        origin: '',
        traceCode: '',
        minTemp: 0,
        maxTemp: 30,
        harvestTime: new Date(),
        description: '',
        auditStatus: null,
        auditComment: '',
        auditTime: null
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        origin: [{ required: true, message: '请输入产地', trigger: 'blur' }],
        minTemp: [{ required: true, message: '请输入最低温度', trigger: 'blur' }],
        maxTemp: [{ required: true, message: '请输入最高温度', trigger: 'blur' }]
      },
      userId: null,
      roleId: null
    };
  },
  created() {
    // 从本地存储获取用户信息
    const userStr = localStorage.getItem('user');
    if (userStr) {
      const user = JSON.parse(userStr);
      this.userId = user.id;
      this.roleId = user.roleId;

      // 检查用户角色是否为果农
      if (this.roleId !== 4) {
        this.$message.warning('只有果农才能访问此页面');
        this.$router.push('/home');
        return;
      }
    } else {
      this.$message.error('未登录或登录已过期');
      this.$router.push('/login');
      return;
    }

    this.loadData();
  },
  methods: {
    // 返回主页
    goToHome() {
      this.$router.push('/home');
    },
    // 加载果农的商品数据
    loadData() {
      this.request.get(`/product/farmer/list?farmerId=${this.userId}`).then(res => {
        if (res.code === '200') {
          this.tableData = res.data || [];
          this.total = this.tableData.length;
        } else {
          this.$message.error(res.msg || '获取商品列表失败');
        }
      });
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
    // 添加商品
    handleAdd() {
      this.dialogTitle = '添加商品';
      this.viewMode = false;
      this.form = {
        name: '',
        price: 0,
        origin: '',
        traceCode: '',
        minTemp: 0,
        maxTemp: 30,
        harvestTime: new Date(),
        description: '',
        auditStatus: null,
        auditComment: '',
        auditTime: null
      };
      this.dialogVisible = true;
    },
    // 查看商品详情
    handleView(row) {
      this.dialogTitle = '商品详情';
      this.viewMode = true;
      this.form = { ...row };
      this.dialogVisible = true;
    },
    // 提交表单
    submitForm() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          // 如果溯源码为空，自动生成溯源码
          if (!this.form.traceCode) {
            this.form.traceCode = 'TC' + Date.now(); // 简单的临时生成方式
          }
          
          this.request.post('/product/farmer/add', this.form, {
            params: {
              userId: this.userId
            }
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('添加商品成功，等待管理员审核');
              this.dialogVisible = false;
              this.loadData();
            } else {
              this.$message.error(res.msg || '添加商品失败');
            }
          });
        } else {
          return false;
        }
      });
    },
    // 表格行样式
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    // 获取审核状态类型
    getAuditStatusType(status) {
      const types = {
        0: 'info',     // 待审核
        1: 'success',  // 审核通过
        2: 'danger'    // 审核拒绝
      };
      return types[status] || 'info';
    },
    // 获取审核状态文本
    getAuditStatusText(status) {
      const texts = {
        0: '待审核',
        1: '审核通过',
        2: '审核拒绝'
      };
      return texts[status] || '未知状态';
    }
  }
};
</script>

<style scoped>
.farmer-product-container {
  padding: 20px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
}

.title-icon {
  font-size: 28px;
  margin-right: 10px;
  color: #67c23a;
}

.button-group {
  display: flex;
  gap: 10px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 